package common;

import java.lang.reflect.Field;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;


/**
 * Depiction: 定时滚动模块图片
 * <p>
 * Modify:
 * <p>
 * Author: Kevin Lynn
 * <p>
 * Create Date：2014年5月13日 下午2:18:27
 * <p>
 * 
 * @version 1.0
 * @since 1.0
 */
public class PagerTask extends Thread {
	private TaskHandler handler  = new TaskHandler();
	private ViewPager   pager;
	private int         total;
	private boolean     isCancel = false;
	private long        duration = 8000;
	
	public PagerTask(ViewPager pager, int total) {
		this.pager = pager;
		this.total = total;
	}
	
	public long getDuration() {
		return duration;
	}
	
	public void setDuration(long duration) {
		this.duration = duration;
	}
	
	public void cancel() {
		this.isCancel = true;
		
	}
	
	@Override
	public void run() {
		while (!isCancel) {
			try {
				sleep(duration);
				handler.sendEmptyMessage(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private class TaskHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (pager != null && !isCancel) {
				try {
					Field mField = ViewPager.class.getDeclaredField("mScroller");
					mField.setAccessible(true);
					Scroller mScroller = new FixedSpeedScroller(pager.getContext(), new AccelerateDecelerateInterpolator());
					mField.set(pager, mScroller);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				int cur = pager.getCurrentItem();
				cur += 1;
				cur = cur >= total ? 0 : cur;
				pager.setCurrentItem(cur, true);
			}
		}
	}//end TaskHandler
	
	class FixedSpeedScroller extends Scroller {
		private int mDuration = 650;
		
		public FixedSpeedScroller(Context context) {
			super(context);
		}
		
		public FixedSpeedScroller(Context context, Interpolator interpolator) {
			super(context, interpolator);
		}
		
		@Override
		public void startScroll(int startX, int startY, int dx, int dy, int duration) {
			// Ignore received duration, use fixed one instead 
			super.startScroll(startX, startY, dx, dy, mDuration);
		}
		
		@Override
		public void startScroll(int startX, int startY, int dx, int dy) {
			// Ignore received duration, use fixed one instead 
			super.startScroll(startX, startY, dx, dy, mDuration);
		}
		
		public void setmDuration(int time) {
			mDuration = time;
		}
		
		public int getmDuration() {
			return mDuration;
		}
	}
}
